package cn.msqweb.impl;


import cn.msqweb.constant.AuthConstants;
import cn.msqweb.factory.LoginStrategyFactory;
import cn.msqweb.mapper.LoginSysUserMapper;
import cn.msqweb.strategy.LoginStrategy;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 自定义的认证流程
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private LoginStrategyFactory loginStrategyFactory;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 从请求头中获取登录的类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        // 判断是否有值
        if (!StringUtils.hasText(loginType)) {
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
        // 从登录策略工厂类中根据登录类型来获取具体的登录策略
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        // 调用登录策略对象的具体登录方法
        return instance.realLogin(username);
    }
}
